Creating A simple Web Server with Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Original: https://tutorialedge.net/post/golang/creating-simple-web-server-with-golang/

--------------------------------------------------------------------------------------------------------------- -------------------------------------------------------

In this tutorial we are focusing on creating a very simple Web server using the Net/http package. If you've ever used something like Node ' s Expressjs or Python ' s Tornado and then you should hopefully see some similarities T o how things is handled.

Creating a Basic Web Server

Ok, so-to-begin with We'll create a very simple Web server that would just return whatever the URL path is of the your query. This is a good base from which we can build on top of.

Package MainImport (      "FMT"  "html"  "log" " net/http ") func  Main () {http. Handlefunc ( "/", func (w http. Responsewriter, R *http. Request) {fmt. fprintf (W,  "Hello,%q", HTML. Escapestring (R.url. Path)}) http. Handlefunc ( "/hi", func (w http. Responsewriter, R *http. Request) {fmt. fprintf (W,  "Hi")}) log. Fatal (http. Listenandserve ( ": 8081", nil)}     

In the above code we essentially define the different handlers. These handlers is what respond to any HTTP request that match the string pattern we define as the first parameter. So essentially whenever a request was made for the home page or http://localhost:8081/, we'll see our first handle R respond as the query matches that pattern.

Running our Server

Ok so now the we ' ve created our own very simplistic server we can try running it by typing go run server.go to our cons Ole. This usually asks me for permission so accept that and then head over to your browser and head to Http://localhost:8081/wo Rld. On the This page, you should hopefully see your query string echoed back to the true "Hello World" fashion.

Adding a bit of complexity

So now that we've got a basic Web server set up, let's try incrementing a counter every time a specific URL is hit. Due to the fact and the Web server is asynchronous, we'll have the counter using a mutex on order to prevent us From being hits with Race-condition bugs.

Package MainImport ("FMT""Log""Net/http""StrConv""Sync")var counterIntvar mutex = &sync. mutex{}FuncEchostring(W http. Responsewriter, R *http. Request) {fmt. fprintf (W, "Hello")} func incrementcounter (w http. Responsewriter, R *http. Request) {Mutex. Lock () counter++fmt. fprintf (W, StrConv. Itoa (counter)) mutex. Unlock ()}func main () {http. Handlefunc ( "/", echostring) http. Handlefunc ( "/increment", Incrementcounter) http. Handlefunc ( "/hi", func (w http. Responsewriter, R *http. Request) {fmt. fprintf (W,  "Hi")}) log. Fatal (http. Listenandserve ( ": 8081", nil)}     

Run this and then navigate to http://localhost:8081/increment and you should see the current count which would be locked, I Ncremented and then unlocked every time a request to that page.

Serving Static Files

Ok, so now that we've set up a simple server in go, it's time to start serving some static files. Create a static folder within your project ' s directory and then create some simple HTML files. For this example I ' m just serving back the following:

 <html> <head> <title >hello world</title> </head> <body>  <h2>hello world! </h2> </body> </HTML>         

Once you ' ve got this and we can then modify our Web server code to use the HTTP. Servefile method. Essentially this would take at the URL of the request made to the server, and if it contains say index.html then it would r Eturn the index.html file, rendered as HTML in the browser. If we were to create an edit.html page and send a request to http://localhost:8081/edit.html then it would retur n Whatever HTML content you choose to put in that edit.html page.

package mainimport ( "FMT"  "log"  "net/http")  func main () {http. Handlefunc ( "/", func (w http. Responsewriter, R *http. Request) {http. Servefile (W, R, R.url. Path[ "/hi", func (w http. Responsewriter, R *http. Request) {fmt. fprintf (W,  "Hi")}) log. Fatal (http. Listenandserve ( ": 8081", nil)}      

Checking it Works

Again run the server and navigate to http://localhost:8081/index.html and you should hopefully see your very simple index. HTML file rendered in the all it ' s glory.

I hope you found this tutorial useful and if you do and then please me know in the comments section below! This was part one of a series of Golang tutorials in which we play around with APIs and creating servers so stay tuned for more!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.