fullstack web app-golang #6

f

So now as we did both our frontend and backend, you may think these should work together.

But there’s a small problem.

We’re gonna need to configure something called CORS in the backend. Again we’re gonna use a library

go get "github.com/rs/cors"

Now in our main.go file.

	//connect to db
	db.Connectmongo()

	// Init router
	r := mux.NewRouter()
	secretHandler := http.HandlerFunc(helpers.AddPost)

	// Route handles & endpoints
	r.HandleFunc("/", helpers.GetAllPosts).Methods("GET")
	r.HandleFunc("/register", helpers.SaveUser).Methods("POST")
	r.HandleFunc("/login", helpers.FindUser).Methods("POST")
	r.Handle("/addpost", helpers.IsAuthorized(secretHandler)).Methods("POST")

	c := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // All origins
		AllowedMethods:   []string{"GET", "POST", "OPTIONS", "PUT", "DELETE"},
		AllowCredentials: true,
		AllowedHeaders: []string{"*"},
	})
	//start the server
	log.Fatal(http.ListenAndServe(":8080", c.Handler(r)))

Also add this line your request Handlers

	w.Header().Set("Access-Control-Allow-Origin", "*")

	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

Now everything is set.

Heres the website that we built

(on mobile view)

whats next?

Obviously I missed some features here. I never added any validation. Like the password should contain atleast one special character etc

And theres no user feedback if anything goes wrong.

So if you want feel free to fork the project, improve it.

And thats it. Thanks

Keep learning 🙂

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: