Certainly! Combining Go as the backend and Vue.js as the frontend is a powerful stack for building modern web applications. Here’s a step-by-step guide to creating a “Hello, World!” application using Go and Vue.js.
Step 1: Set Up Go Backend
Install Go:
- Download and install Go from the official website: https://golang.org/dl/.
- Verify the installation by running:
go version
Create a Go Backend:
- Create a new directory for your project:
mkdir go-vue-hello-world cd go-vue-hello-world
- Inside the project directory, create a Go file (e.g.,
main.go
) with the following code:package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") }) fmt.Println("Server is running on :8080...") http.ListenAndServe(":8080", nil) }
- Save the file and run the Go application:
go run main.go
- Open a web browser and go to http://localhost:8080. You should see “Hello, World!”.
Step 2: Set Up Vue.js Frontend
Install Node.js and npm:
- Download and install Node.js from the official website: https://nodejs.org/.
- Verify the installation by running:
node -v npm -v
Create a Vue.js Frontend:
- Inside the project directory, create a new directory for the frontend:
mkdir frontend cd frontend
- Initialize a new Vue.js project:
npm init -y
- Install Vue.js and Vue CLI:
npm install vue npm install -g @vue/cli
- Create a new Vue component. In the
src
directory, create a file namedApp.vue
with the following content:<template> <div id="app"> <h1>{{ message }}</h1> </div> </template> <script> exportdefault { data() { return { message: "Hello, World from Vue.js!", }; }, }; </script><style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; text-align: center;color: #2c3e50; margin-top: 60px; } </style>
- Modify the
src/main.js
file to import and use theApp.vue
component:import Vue from "vue"; import App from "./App.vue"; Vue.config.productionTip = false;new Vue({ render: (h) => h(App), }).$mount("#app");
- Open a terminal in the
frontend
directory and run the Vue.js application:npm run serve
- Open a web browser and go to http://localhost:8081. You should see “Hello, World from Vue.js!”.
Step 3: Connect Go Backend and Vue.js Frontend
- In the
frontend
directory, opensrc/App.vue
and modify thedata
section:data() { return { message: "Loading...", }; }, mounted() {fetch("http://localhost:8080") .then((response) => response.text()) .then((data) => {this.message = data; }); },
- Stop the Vue.js development server (if it’s running) and restart it:
npm run serve
- Open a web browser and go to http://localhost:8081. You should see “Hello, World!” fetched from the Go backend.
Congratulations! You’ve successfully created a “Hello, World!” application using Go as the backend and Vue.js as the frontend. This serves as a foundation for building more complex web applications with this powerful stack.
Credit Image : Image by freepik