Esempio n. 1
0
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)
}
// -- 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))
}
Esempio n. 3
0
func main() {
	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		&rest.Route{"GET", "/users/:id", GetUser},
	)
	log.Fatal(spdy.ListenAndServeTCP(":8080", &handler))
}
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")
		}
	}
}
Esempio n. 5
0
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
}
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)
}
func newHandler() rest.ResourceHandler {
	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		&rest.Route{"GET", "/verify/", getEmailVerify},
	)
	return handler
}
Esempio n. 8
0
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()
}
Esempio n. 9
0
func main() {
	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		&rest.Route{"POST", "/hashes", Hash},
	)
	http.ListenAndServe(":8080", &handler)
}
Esempio n. 10
0
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))
}
Esempio n. 11
0
func main() {
	handler := rest.ResourceHandler{}
	handler.SetRoutes(
		&rest.Route{"GET", "/message", func(w rest.ResponseWriter, req *rest.Request) {
			w.WriteJson(&Message{
				Body: "Hello World!",
			})
		}},
	)
	http.ListenAndServe(":8080", &handler)
}
Esempio n. 12
0
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)
}
Esempio n. 13
0
func main() {

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
		DisableJsonIndent:        true,
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/stream", StreamThings},
	)
	http.ListenAndServe(":8080", &handler)
}
Esempio n. 14
0
func main() {

	handler := rest.ResourceHandler{
		PreRoutingMiddlewares: []rest.Middleware{
			&MyCorsMiddleware{},
		},
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/countries", GetAllCountries},
	)
	http.ListenAndServe(":8080", &handler)
}
Esempio n. 15
0
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)
}
Esempio n. 16
0
func main() {
	handler := rest.ResourceHandler{
		EnableStatusService: true,
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/.status",
			func(w rest.ResponseWriter, r *rest.Request) {
				w.WriteJson(handler.GetStatus())
			},
		},
	)
	http.ListenAndServe(":8080", &handler)
}
Esempio n. 17
0
func main() {

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	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.ListenAndServe(":8080", &handler)
}
Esempio n. 18
0
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))

}
Esempio n. 19
0
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)
}
Esempio n. 20
0
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)
}
Esempio n. 21
0
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)
}
Esempio n. 22
0
File: web.go Progetto: rysenko/goat
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))
}
Esempio n. 23
0
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)
}
Esempio n. 24
0
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")
}
Esempio n. 25
0
func main() {

	handler := rest.ResourceHandler{
		PreRoutingMiddlewares: []rest.Middleware{
			&MyAuthBasicMiddleware{
				Realm:    "Administration",
				UserId:   "admin",
				Password: "******",
			},
		},
	}
	handler.SetRoutes(
		&rest.Route{"GET", "/countries", GetAllCountries},
	)
	http.ListenAndServe(":8080", &handler)
}
Esempio n. 26
0
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))
}
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)
}
func BenchmarkGoJsonRest_Simple(b *testing.B) {
	handler := rest.ResourceHandler{
		DisableJsonIndent: true,
		DisableXPoweredBy: true,
		Logger:            log.New(ioutil.Discard, "", 0),
	}
	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)
	}
}
func main() {
	api := Api{}
	api.initDB()

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		rest.RouteObjectMethod("GET", "/api/entries", &api, "GetAllEntries"),
		rest.RouteObjectMethod("POST", "/api/entries", &api, "PostEntry"),
		rest.RouteObjectMethod("GET", "/api/entries/:id", &api, "GetEntry"),
		//rest.RouteObjectMethod("PUT", "/api/entriess/:id", &api, "PutEntry"),
		rest.RouteObjectMethod("DELETE", "/api/entries/:id", &api, "DeleteEntry"),
	)

	http.ListenAndServe(":8082", &handler)
}
Esempio n. 30
0
func main() {

	ports := ports{
		Store: map[string]*Port{},
	}

	handler := rest.ResourceHandler{
		EnableRelaxedContentType: true,
	}
	handler.SetRoutes(
		rest.RouteObjectMethod("GET", "/ports", &ports, "GetAllPorts"),
		rest.RouteObjectMethod("POST", "/ports", &ports, "PostPort"),
		rest.RouteObjectMethod("GET", "/ports/:id/:name", &ports, "GetPort"),
		rest.RouteObjectMethod("PUT", "/ports/:id", &ports, "PutPort"),
		rest.RouteObjectMethod("DELETE", "/ports/:id", &ports, "DeletePort"),
	)
	http.ListenAndServe(":8080", &handler)
}