作者:parisholle
项目:go-json-rest-example
func main() {
handler := rest.ResourceHandler{
EnableStatusService: true,
}
auth := &rest.AuthBasicMiddleware{
Realm: "test zone",
Authenticator: func(userId string, password string) bool {
if userId == "admin" && password == "admin" {
return true
}
return false
},
}
handler.SetRoutes(
&rest.Route{"GET", "/countries", GetAllCountries},
&rest.Route{"GET", "/.status",
auth.MiddlewareFunc(
func(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(handler.GetStatus())
},
),
},
)
http.ListenAndServe(":8080", &handler)
}
作者:divideandconque
项目:go-celery-ap
// -- Main function --
// Sets up server and Tasks struct, starts listening on 8080
func main() {
//set flags
configFile := flag.String("config", "", "An optional filepath for a config file.")
flag.Parse()
if *configFile != "" {
log.Printf("configFile: " + *configFile)
}
//setup tasks
tasks := new(Tasks)
tasks.ConfigFile = *configFile
//load config
tasks.SetupAmqpConnection()
//setup resource handler and routes
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
err := handler.SetRoutes(
rest.RouteObjectMethod("POST", "/tasks", tasks, "PostTask"),
)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", &handler))
}
作者:kosud
项目:golang-mux-benchmar
func BenchmarkGoJsonRest_Middleware(b *testing.B) {
handler := rest.ResourceHandler{
DisableJsonIndent: true,
DisableXPoweredBy: true,
Logger: log.New(ioutil.Discard, "", 0),
PreRoutingMiddlewares: []rest.Middleware{
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
},
}
handler.SetRoutes(
&rest.Route{"GET", "/action", goJsonRestHelloHandler},
)
rw, req := testRequest("GET", "/action")
b.ResetTimer()
for i := 0; i < b.N; i++ {
handler.ServeHTTP(rw, req)
if rw.Code != 200 {
panic("no good")
}
}
}
作者:AbdulZai
项目:cher-am
func MakeHandler(api cheramiapi.Api, disableLogs bool) (rest.ResourceHandler, error) {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
DisableLogger: disableLogs,
}
err := handler.SetRoutes(
&rest.Route{"POST", "/signup", api.Signup},
&rest.Route{"POST", "/sessions", api.Login},
&rest.Route{"DELETE", "/sessions", api.Logout},
&rest.Route{"GET", "/users/:handle", api.GetUser},
&rest.Route{"PATCH", "/users/:handle", api.EditUser},
&rest.Route{"GET", "/users", api.SearchForUsers},
&rest.Route{"GET", "/messages", api.GetMessages},
&rest.Route{"GET", "/messages/:id", api.GetMessageById},
&rest.Route{"POST", "/messages", api.NewMessage},
&rest.Route{"PATCH", "/messages/:id", api.EditMessage},
&rest.Route{"DELETE", "/messages", api.DeleteMessage},
&rest.Route{"POST", "/joindefault", api.JoinDefault},
&rest.Route{"POST", "/join", api.Join},
&rest.Route{"POST", "/block", api.BlockUser},
&rest.Route{"POST", "/circles", api.NewCircle},
&rest.Route{"GET", "/circles", api.SearchCircles},
)
return handler, err
}
作者:kosud
项目:golang-mux-benchmar
func BenchmarkGoJsonRest_Composite(b *testing.B) {
namespaces, resources, requests := resourceSetup(10)
handler := rest.ResourceHandler{
DisableJsonIndent: true,
DisableXPoweredBy: true,
Logger: log.New(ioutil.Discard, "", 0),
PreRoutingMiddlewares: []rest.Middleware{
&benchmarkGoJsonRestCompositeMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
&benchmarkGoJsonRestMiddleware{},
},
}
routes := make([]*rest.Route, 0, len(namespaces)*len(resources)*5)
for _, ns := range namespaces {
for _, res := range resources {
routes = append(routes, &rest.Route{"GET", "/" + ns + "/" + res, goJsonRestHelloHandler})
routes = append(routes, &rest.Route{"POST", "/" + ns + "/" + res, goJsonRestHelloHandler})
routes = append(routes, &rest.Route{"GET", "/" + ns + "/" + res + "/:id", goJsonRestHelloHandler})
routes = append(routes, &rest.Route{"PUT", "/" + ns + "/" + res + "/:id", goJsonRestHelloHandler})
routes = append(routes, &rest.Route{"DELETE", "/" + ns + "/" + res + "/:id", goJsonRestHelloHandler})
}
}
handler.SetRoutes(routes...)
benchmarkRoutes(b, &handler, requests)
}
作者:taterbas
项目:smtp-callback-verificatio
func newHandler() rest.ResourceHandler {
handler := rest.ResourceHandler{}
handler.SetRoutes(
&rest.Route{"GET", "/verify/", getEmailVerify},
)
return handler
}
作者:roongr2k
项目:time_tracker_ap
func TestHandler(t *testing.T) {
handler := rest.ResourceHandler{
DisableJsonIndent: true,
ErrorLogger: log.New(ioutil.Discard, "", 0),
}
handler.SetRoutes(
&rest.Route{"POST", "/api/coach/checkin",
func(w rest.ResponseWriter, r *rest.Request) {
w.WriteHeader(http.StatusCreated)
data := map[string]string{"id": "53f87e7ad18a68e0a884d31e"}
w.WriteJson(data)
},
},
&rest.Route{"POST", "/api/coach/checkout",
func(w rest.ResponseWriter, r *rest.Request) {
w.WriteHeader(http.StatusAccepted)
},
},
)
recorded := test.RunRequest(t, &handler, test.MakeSimpleRequest(
"POST", "http://www.sprint3r.com/api/coach/checkin", &map[string]string{"name": "iporsut", "league": "dtac"}))
recorded.CodeIs(201)
recorded.ContentTypeIsJson()
recorded.BodyIs(`{"id":"53f87e7ad18a68e0a884d31e"}`)
recorded = test.RunRequest(t, &handler, test.MakeSimpleRequest(
"POST", "http://www.sprint3r.com/api/coach/checkout", &map[string]string{"name": "iporsut", "league": "dtac"}))
recorded.CodeIs(202)
recorded.ContentTypeIsJson()
}
作者:rdegge
项目:cryptly-ap
func main() {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
handler.SetRoutes(
&rest.Route{"POST", "/hashes", Hash},
)
http.ListenAndServe(":8080", &handler)
}
作者:ohlinu
项目:golang-snippet-c
func LaunchRestServer() {
//加载rest配置
//config, err := ConfigFromFile(configPath)
//if err != nil {
// panic(err.Error())
//}
var logErr error
restLog, logErr := os.OpenFile("./log/rest_access.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
if logErr != nil {
panic(logErr)
}
defer restLog.Close()
restErrLog, logErr := os.OpenFile("./log/rest_error.log", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
if logErr != nil {
panic(logErr)
}
defer restErrLog.Close()
handler := rest.ResourceHandler{
PreRoutingMiddlewares: []rest.Middleware{
&rest.AuthBasicMiddleware{
Realm: "eggs zone",
//AllowedMethods: []string{"GET", "POST", "PUT"},
Authenticator: func(userId string, password string) bool {
if userId == "orp" && password == "orp" {
return true
}
return false
},
},
},
Logger: log.New(restLog, "", 0),
ErrorLogger: log.New(restErrLog, "", log.Ldate|log.Ltime|log.Llongfile),
}
err := handler.SetRoutes(
//register
&rest.Route{"POST", "/register/module", postRegisterModuleTask},
&rest.Route{"GET", "/register/module", getRegisterModuleTask},
//&rest.Route{"POST", "/register/package", postRegisterPackageTask},
//&rest.Route{"GET", "/register/package", getRegisterPackageTask},
//packer
//&rest.Route{"POST", "/packer/:taskId", postPackerTask},
//&rest.Route{"GET", "/packer/:taskId", getPackerTask},
//version
//&rest.Route{"GET", "/version/diff/:vnew/:vold", getVersionDiffTask},
)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", &handler))
}
作者:parisholle
项目:go-json-rest-example
func init() {
handler := rest.ResourceHandler{}
handler.SetRoutes(
&rest.Route{"GET", "/countries", GetAllCountries},
&rest.Route{"POST", "/countries", PostCountry},
&rest.Route{"GET", "/countries/:code", GetCountry},
&rest.Route{"DELETE", "/countries/:code", DeleteCountry},
)
http.Handle("/", &handler)
}
作者:palania
项目:GO_TaskManage
func main() {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
handler.SetRoutes(
&rest.Route{"POST", "/task/add", CreateTask},
&rest.Route{"GET", "/task/list", ReadAllTasks},
&rest.Route{"GET", "/task/:id", ReadTask},
&rest.Route{"POST", "/task/:id", UpdateTask},
&rest.Route{"POST", "/task/delete/:id", DeleteTask},
)
http.ListenAndServe(":8080", &handler)
}
作者:mehulsbhat
项目:goteliu
func main() {
api := Api{}
api.InitDB()
api.InitSchema()
handler := rest.ResourceHandler{
EnableStatusService: true,
EnableRelaxedContentType: true,
PreRoutingMiddlewares: []rest.Middleware{
&rest.AuthBasicMiddleware{
Realm: "test zone",
Authenticator: func(userId string, password string) bool {
if userId == "admin" && password == "admin" {
return true
}
return false
},
},
},
}
svmw := SemVerMiddleware{
MinVersion: "1.2.0",
MaxVersion: "3.0.0",
}
err := handler.SetRoutes(
&rest.Route{"GET", "/#version/countries", svmw.MiddlewareFunc(GetAllCountries)},
&rest.Route{"POST", "/countries", PostCountry},
&rest.Route{"GET", "/countries/:code", GetCountry},
&rest.Route{"DELETE", "/countries/:code", DeleteCountry},
&rest.Route{"GET", "/.status",
func(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(handler.GetStatus())
},
},
// ORM
&rest.Route{"GET", "/reminders", api.GetAllReminders},
&rest.Route{"POST", "/reminders", api.PostReminder},
&rest.Route{"GET", "/reminders/:id", api.GetReminder},
&rest.Route{"PUT", "/reminders/:id", api.PutReminder},
&rest.Route{"DELETE", "/reminders/:id", api.DeleteReminder},
)
if err != nil {
log.Fatal(err)
}
http.Handle("/api/", http.StripPrefix("/api", &handler))
log.Fatal(http.ListenAndServe(":8080", nil))
// log.Fatal(http.ListenAndServe(":8080", &handler))
}
作者:felipewe
项目:osin-mongo-storag
func setupRestAPI(router *mux.Router, oAuth *oAuthHandler) {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
PreRoutingMiddlewares: []rest.Middleware{oAuth},
}
handler.SetRoutes(
&rest.Route{"GET", "/api/me", func(w rest.ResponseWriter, req *rest.Request) {
data := context.Get(req.Request, USERDATA)
w.WriteJson(&data)
}},
)
router.Handle("/api/me", &handler)
}
作者:roofimo
项目:gorest-json-mg
func main() {
mongoPersister := MongoPersister{}
handler := rest.ResourceHandler{}
handler.SetRoutes(
&rest.Route{"GET", "/api/v1/change_pk", func(w rest.ResponseWriter, req *rest.Request) {
var longBook Book = Book{Title: "Harry Potter", Author: "JK Rolling", Pages: 1000}
mongoPersister.InsertPerson()
w.WriteJson(&Message{
Body: longBook.CategoryByLength(),
})
}},
)
http.ListenAndServe(":8080", &handler)
}
作者:priyanka8
项目:Web-service-using-G
func main() {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
handler.SetRoutes(
&rest.Route{"GET", "/task/list", GetAllTasks},
&rest.Route{"POST", "/task/add", PostTask},
&rest.Route{"GET", "/task/:taskdesc", GetTask},
&rest.Route{"POST", "/task/:taskdesc", UpdateTask},
&rest.Route{"DELETE", "/task/:taskdesc", DeleteTask},
)
http.ListenAndServe(":8080", &handler)
}
作者:rysenk
项目:goa
func main() {
handler := rest.ResourceHandler{}
err := handler.SetRoutes(
&rest.Route{"GET", "/", func(w rest.ResponseWriter, req *rest.Request) {
w.WriteJson(&Message{
Body: "Hello World!",
})
}},
)
if err != nil {
log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), &handler))
}
作者:kmanle
项目:golang-gri
func StartClientApi() {
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
//api := clientApi{}
err := handler.SetRoutes(
rest.RouteObjectMethod("POST", "/jobs", api, "CreateJob"),
)
if err != nil {
log.Fatal(err)
}
api.server = manners.NewServer()
glog.Info("client api starting")
api.server.ListenAndServe(":8080", &handler)
}
作者:xjplk
项目:smsadapte
func main() {
path := flag.String("config", "./smsadapter.conf", "设置配置文件的路径")
flag.Parse()
*path = filepath.FromSlash(*path)
c, err := goconfig.LoadConfigFile(*path)
if err != nil {
log.Fatal(err)
}
ip, iperr := c.GetValue("local", "listen")
if iperr != nil {
log.Printf("%v use default:0.0.0.0", iperr)
ip = "0.0.0.0"
}
port, porterr := c.Int("local", "port")
if porterr != nil {
log.Panicf("%v,use default:8500", porterr)
port = 8500
}
smssender := sms.NewSmsHttp()
smssender.Init(c)
fmt.Println("listen on " + ip + ":" + strconv.Itoa(port))
handler := rest.ResourceHandler{}
errx := handler.SetRoutes(
&rest.Route{"GET", "/message", func(w rest.ResponseWriter, req *rest.Request) {
w.WriteJson(&Message{
Body: "Hello World!",
})
}},
&rest.Route{"GET", "/sms/send", func(w rest.ResponseWriter, req *rest.Request) {
w.Header().Set("Content-Type", "Application/json; charset=utf-8")
phone := req.FormValue("phone")
password := req.FormValue("password")
rsp := smssender.Send(phone, password)
w.WriteJson(rsp)
}},
)
if errx != nil {
log.Fatal(errx)
}
log.Fatal(http.ListenAndServe(ip+":"+strconv.Itoa(port), &handler))
fmt.Println("exit1")
}
作者:jgoodal
项目:log-serve
func main() {
var port int
var logpath string
// configure command line flags
flag.IntVar(&port, "port", 8080, "HTTP Server Port")
flag.StringVar(&filepath, "filepath", "output.json", "Output JSON file path")
flag.StringVar(&logpath, "logpath", "log-server.log", "Log file path")
flag.Parse()
// set up logging
l, err := os.OpenFile(logpath, os.O_RDWR|os.O_CREATE, 0644)
defer l.Close()
if err != nil {
log.Fatalf("error opening log file: %v", err)
}
logger := log.New(io.Writer(l), "", 0)
// set up HTTP server
httpAddr := fmt.Sprintf(":%v", port)
logger.Printf("Listening on %v", httpAddr)
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
EnableGzip: true,
EnableLogAsJson: true,
Logger: logger,
PreRoutingMiddlewares: []rest.Middleware{
&rest.CorsMiddleware{
RejectNonCorsRequests: false,
OriginValidator: func(origin string, request *rest.Request) bool {
return true
},
AllowedMethods: []string{"GET", "POST"},
AllowedHeaders: []string{"Accept", "Content-Type", "X-Requested-With"},
AccessControlAllowCredentials: true,
AccessControlMaxAge: 3600,
},
},
}
handler.SetRoutes(
&rest.Route{"POST", "/log", PostLogHandler},
&rest.Route{"GET", "/logs", GetLogsHandler},
)
log.Fatal(http.ListenAndServe(httpAddr, &handler))
}
作者:sohamsankara
项目:go-database-driver
func main() {
api := Api{}
api.initDB()
handler := rest.ResourceHandler{
EnableRelaxedContentType: true,
}
handler.SetRoutes(
rest.RouteObjectMethod("GET", "/api/users", &api, "GetAllUsers"),
rest.RouteObjectMethod("POST", "/api/users", &api, "PostUser"),
rest.RouteObjectMethod("GET", "/api/users/:id", &api, "GetUser"),
/*&rest.RouteObjectMethod("PUT", "/api/users/:id", &api, "PutUser"),*/
rest.RouteObjectMethod("DELETE", "/api/users/:id", &api, "DeleteUser"),
)
http.ListenAndServe(":"+HTTPREST_SERVERPORT, &handler)
}