Creating A Simple Web Server With Golang

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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

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

In this tutorial we’ll be 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, then you should hopefully see some similarities to how things are handled.

Creating a Basic Web Server

Ok, so to begin with we’ll create a very simple web server that will just return whatever the URL path is of your query. This will be 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 two different Handlers. These handlers are what respond to any http request that match the string pattern we define as the first parameter. So essentially whenever a request is made for the home page or http://localhost:8081/, we’ll see our first handler respond as the query matches that pattern.

Running Our Server

Ok so now that we’ve created our own very simplistic server we can try running it by typing go run server.go into our console. This usually asks me for permission so accept that and then head over to your browser and head to http://localhost:8081/world. On this page you should hopefully see your query string echoed back to you in 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 that the web server is asynchronous, we’ll have to guard our counter using a mutex in order to prevent us from being hit with race-condition bugs.

package mainimport ("fmt""log""net/http""strconv""sync")var counter intvar mutex = &sync.Mutex{}func echoString(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 will be locked, incremented and then unlocked every time you make 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 then we can then modify our web server code to use the http.ServeFile method. Essentially this will take in the url of the request made to the server, and if it contains say index.html then it would return 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 return 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[1:])})http.HandleFunc("/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 all it’s glory.

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.