How to implement root endpoint?

0100

To implement a root endpoint (/) in a web application, you can use various frameworks depending on the programming language. Here are examples in a few popular languages:

Node.js (Express)

const express = require('express');
const app = express();
const port = 8080;

app.get('/', (req, res) => {
  res.send('Welcome to the root endpoint!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Python (Flask)

from flask import Flask

app = Flask(__name__)

@app.route('/')
def root():
    return 'Welcome to the root endpoint!'

if __name__ == '__main__':
    app.run(port=8080)

Java (Spring Boot)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping("/")
    public String root() {
        return "Welcome to the root endpoint!";
    }
}

Go (net/http)

package main

import (
    "fmt"
    "net/http"
)

func rootHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Welcome to the root endpoint!")
}

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

Summary

In each example, the application listens on port 8080 and responds with a message when the root endpoint (/) is accessed. You can customize the response as needed. If you have a specific language or framework in mind, let me know for more tailored guidance!

0 Comments

no data
Be the first to share your comment!