如何使用内容类型为application / hal + json的Rocket处理程序进行响应?

时间:2017-09-02 19:36:23

标签: json rust serde rust-rocket

我有一个用Rocket编写的项目,其端点/foo返回application/json中的数据。我使用的是rocket,rocket_codegen,serde和serde_json。

#[get("/foo")]
fn foo() -> Json {
    Json(json!({
        "foo": 1
    }))
}

这很好用,但我需要回复application/hal+json所以我想我需要写自己的回复,但我失败了。如何使用Content-Type application/hal+json返回我的JSON?

1 个答案:

答案 0 :(得分:1)

我在项目聊天中获得了一些帮助,解决方案是:

@Controller
public class FileController {

    @Autowired
    private FileRepository fileRepository;

    @Autowired
    private AccountRepository accountRepository;

    @RequestMapping(value = "/files", method = RequestMethod.GET)
    public String list(Authentication authentication, Model model) {
        model.addAttribute("files", accountRepository.findByUsername(authentication.getName()).getFileObjects());
        return "files";
    }

    @RequestMapping(value = "/files/{id}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> viewFile(@PathVariable Long id) {
        //1. get object or name account name
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentPrincipalName = authentication.getName();
        //2. check if the file account is of the same name
        FileObject fo = fileRepository.findOne(id);
        if((fo.getAccount().getUsername()).equals(currentPrincipalName)) {

            System.out.println("WHAT AM I SUPPOSED TO DO!?");


        }



        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(fo.getContentType()));
        headers.add("Content-Disposition", "attachment; filename=" + fo.getName());
        headers.setContentLength(fo.getContentLength());

        return new ResponseEntity<>(fo.getContent(), headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/files", method = RequestMethod.POST)
    public String addFile(Authentication authentication, @RequestParam("file") MultipartFile file) throws IOException {
        Account account = accountRepository.findByUsername(authentication.getName());


        FileObject fileObject = new FileObject();
        fileObject.setContentType(file.getContentType());
        fileObject.setContent(file.getBytes());
        fileObject.setName(file.getOriginalFilename());
        fileObject.setContentLength(file.getSize());
        fileObject.setAccount(account);

        fileRepository.save(fileObject);


        return "redirect:/files";
    }

    @RequestMapping(value = "/files/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable Long id) {
        fileRepository.delete(id);
        return "redirect:/files";
    }
}
相关问题