Go语言实战案例——在线字典|青训营

59 阅读1分钟

在线字典是一个实用的应用,以下是一个使用Go语言实现在线字典的案例,也可作为你的学习笔记。

一、准备工作

在开始编程之前,我们需要先安装Go环境,并引入必要的库。这个项目中我们会用到"net/http"和"encoding/json"两个库。

二、创建词典数据

在开始编写代码之前,我们需要先创建一个词典数据。这里我们使用map数据类型来存储词典,每个单词及其解释都作为一个键值对存在。

var dictionary = map[string]string{
	"go":      "Go is a statically typed, compiled programming language designed at Google.",
	"python":  "Python is an interpreted, high-level and general-purpose programming language.",
	"java":    "Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.",
}
复制代码

三、创建HTTP服务

创建一个HTTP服务并监听8080端口,接受客户端的请求。

http.HandleFunc("/", handleRequest)
log.Fatal(http.ListenAndServe(":8080", nil))
复制代码

四、处理请求

当收到一个HTTP请求时,我们需要根据请求的URL路径来查找相应的单词。

func handleRequest(w http.ResponseWriter, r *http.Request) {
	word := r.URL.Path[1:]
	definition, ok := dictionary[word]
	if !ok {
		http.Error(w, "Word not found", http.StatusNotFound)
		return
	}

	json.NewEncoder(w).Encode(map[string]string{"word": word, "definition": definition})
}
复制代码

五、完整代码

package main

import (
	"encoding/json"
	"log"
	"net/http"
)

var dictionary = map[string]string{
	"go":      "Go is a statically typed, compiled programming language designed at Google.",
	"python":  "Python is an interpreted, high-level and general-purpose programming language.",
	"java":    "Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible.",
}

func main() {
	http.HandleFunc("/", handleRequest)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	word := r.URL.Path[1:]
	definition, ok := dictionary[word]
	if !ok {
		http.Error(w, "Word not found", http.StatusNotFound)
		return
	}

	json.NewEncoder(w).Encode(map[string]string{"word": word, "definition": definition})
}
复制代码

此在线字典程序简单易懂,可以让你更好地理解Go语言在Web开发中的应用。