Golang Base HTTP Server

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

This is just a record of your own learning process.

First, you need to introduce the "Net/http" package

import "net/http"

After importing the related package, the next step is to initialize it in the main function, and a few lines of code will build the good one HTTP server

err := http.ListenAndServe(":8080", nil)if err != nil {fmt.Println("服务启动失败。")}

Above just set up a service, and there is no function, below I also want to add the corresponding handlefunc so that can respond to related requests. As follows:

First, set up a Handlefunc callback function

func homeHandler(w http.ResponseWriter, h *http.Request) {w.Write([]byte("hello ying32!"))}

Then initially bind in the main function, remember to be sure to do so in http. Listenandserve before binding, here I bind the root directory "/", when access to Local: http://127.0.0.1:8080 can be called to the Homehandler function.

http.HandleFunc("/", homeHandler)

Alternatively, you can use http. Fileserver to quickly bind a directory as a static file service.

http.Handle("/static", http.FileServer(http.Dir("你的目录")))
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.