Build a web service from scratch using the Go language, including key steps such as environment setup, routing, middleware usage, JSON and form data processing, and more, providing rich code examples.
Concerned about TechLead, Dr. Fudan, sharing full-dimension development technology in cloud service field. He has 10+ years of experience in Internet service architecture, AI product development and team management, member of Fudan Robotics Intelligence Laboratory, expert in judging national university tournaments, published several academic papers in SCI core journals, senior architect certified by AliCloud, and R&D leader of AI products with hundreds of millions of revenue.
Environment Setup
Before we start development, we need to make sure that the Go language development environment is installed in our local environment.
Installing the Go language
It can be done from theGo Language Official WebsiteDownload the installation package for your operating system and follow the guide on the official website.
Configuring Development Tools
It is recommended to use VS Code or GoLand for Go language development. Here are the steps to configure VS Code:
- Install the VS Code editor.
- Install the Go plugin: open VS Code, go to the plugin marketplace, search for and install it
Go
Plug-ins. - Configure the Go development environment: Make sure the Go language installation path has been added to the system environment variables.
Creating a Project Structure
Create a new project folder and initialize the Go module.
mkdir simple-web-server
cd simple-web-server
go mod init simple-web-server
Creating an HTTP server
We will use the Go standard librarynet/http
to create a simple HTTP server.
Introducing the necessary packages
Create a file in the project root directory calledfile and introduce the necessary packages.
package main
import (
"fmt"
"net/http"
)
Creating simple HTTP handler functions
We need to create a handler function to respond to HTTP requests.
func helloHandler(w , r *) {
(w, "Hello, World!")
}
Create and start the HTTP server
existmain
function, we will create the HTTP server and specify the port number.
func main() {
("/", helloHandler) // set up the route
("Starting server at port 8080")
if err := (":8080", nil); err ! = nil {
("Error starting server:", err)
}
}
completeThe documents are listed below:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w , r *) {
(w, "Hello, World!")
}
func main() {
("/", helloHandler) // Setting up routing
("Starting server at port 8080")
if err := (":8080", nil); err != nil {
("Error starting server:", err)
}
}
Operations Server
Run the following command in a terminal to start the server:
go run
Open your browser and visithttp://localhost:8080
You will see a page that says "Hello, World!".
Routing and Request Handling
We will extend the HTTP server with more routing and handler functions.
Adding a new route
Add a new handler function to handle/greet
Path requests.
func greetHandler(w , r *) {
name := ().Get("name")
if name == "" {
name = "Guest"
}
(w, "Hello, %s!", name)
}
Registering a new route
existmain
function to register a new route:
func main() {
("/", helloHandler) // Setting up root path routing
("/greet", greetHandler) // set up/greetPath Routing
("Starting server at port 8080")
if err := (":8080", nil); err != nil {
("Error starting server:", err)
}
}
Testing new routes
Restart the server and access thehttp://localhost:8080/greet?name=Go
The page will say "Hello, Go!".
Processing form data
We will extend the server to handle POST requests and form data.
Creating HTML forms
Add a new handler function to display HTML forms:
func formHandler(w , r *) {
html := `<html><body>
<form method="POST" action="/submit">
<label for="name">Name:</label>
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body></html>`
(w, html)
}
Handling form submissions
Add a new handler function to handle form submissions:
func submitHandler(w , r *) {
if != {
(w, "Invalid request method", )
return
}
name := ("name")
(w, "Form submitted! Hello, %s!", name)
}
Registering a new route
existmain
function to register a new route:
func main() {
("/", helloHandler) // Setting up root path routing
("/greet", greetHandler) // set up/greetPath Routing
("/form", formHandler) // set up/formPath Routing
("/submit", submitHandler) // set up/submitPath Routing
("Starting server at port 8080")
if err := (":8080", nil); err != nil {
("Error starting server:", err)
}
}
Test Form Functionality
Restart the server and access thehttp://localhost:8080/form
If you fill in the form and submit it, the page will display "Form submitted! Hello, [your name]!"
With the above steps, we have successfully created a simple Go Web Service with routing processing and form data handling.
Stay tuned if this helps!
TeahLead KrisChang, 10+ years of Internet and AI experience, 10+ years of technical and business team management experience, Tongji Software Engineering Bachelor's Degree, Fudan Engineering Management Master's Degree, AliCloud Certified Cloud Services Senior Architect, Hundreds of millions of revenue AI product business leader.